<?php
	/**
	 * @ignore
	 */
	if(defined("def_".__FILE__)) return;	
	define("def_".__FILE__,"def_".__FILE__);
	
	require_once(APL_ROOT."/apl_constants.php");
  	require_once(APL_ROOT."/db/apl_db_".APL_DB_PROVIDER.".php");
  
	/**
	* Base class to perform search operations
	*
	* @package apl
	* @subpackage database
	*/
	class AplSearch
	{
	    private $Db;
	    private $Words;
	    private $resultPerPage;
	    /**
	     * Sets the number of results per page
	     *
	     * @param Integer $AValue
	     */
	    public function setResultsPerPage( $AValue )
	    {
	        $this->resultPerPage = empty($AValue)?$this->Result_Per_Page:$AValue;
	    }
	    /**
	     * Returns the number results per page
	     *
	     * @return Integer
	     */
	    public function getResultsPerPage(  )
	    {
	        return $this->resultPerPage;
	    }
	    /**
	     * Prepares class for search
	     *
	     * @param String $Keywords : Words seperated by spaces ( "keyword1 keyword3 key5")
	     */
	    public function prepare( $Keywords )
	    {
	        unset( $this->Words );
	        $this->Words = explode( " ",$Keywords );
	        /*
	         * TODO : Parse for logical operators
	         */
	    }
	    /**
	     * Scans the fields of the table to find rows 
	     *
	     * @param String $paramTableName : Table to search
	     * @param Array $paramFieldList  : Array Of Fields to search
	     * @param String $paramKeyFieldName : Primary key field of the table
	     * @param Integer $paramPage :Resultset Page 
	     * @return Array : Returns array of primary keys
	     */
	    public function scan( $paramTableName, $paramFieldList,$paramKeyFieldName,$paramPage=1 )
	    {
	        $mySQL = 'Select '.$paramKeyFieldName.' From '.$paramTableName.' ';
	        $myWhere = 'Where ';
	        foreach( $paramFieldList as $Tbl_Field)
	        {
	            $tWhere = '';
	            foreach( $this->Words as $w )
	            {
	                if( !empty($tWhere) )
	                    $tWhere.=' OR ';
	                $tWhere .= "(".$Tbl_Field." Like '%".$w."%') ";
	            }
	            if( !empty($myWhere) )
	                $myWhere .= ' OR ';
	            $myWhere .= $tWhere;
	        }
	        $mySQL.=$myWhere;
	        $resultIds = array();
	        try{
	            $this->Db->open($mySQL,$this->Result_Per_Page,$paramPage );
	            do{
	                $Result_Set = $this->Db->fetch();
	                $resultIds[] = $Result_Set[$paramKeyFieldName];
	            }while($this->Db->nextRecord() );
	            
	            return $resultIds;
	            
	        }catch(Exception $e)
	        {
	            if( $e->getCode() != EX_DB_NO_ROWS )
	                echo "<h1>".$e->getMessage()."</h1>";
	                
	        }
	        return null;
	    }
	    
	}
?>